import http from 'wechat-http'

http.baseURL = 'https://slwl-api.itheima.net'
// 请求拦截器
http.intercept.request = (options) => {
  // 指定默认的头信息
  const defaultHeader = {}
  const token = getApp().getToken()
  // 权限认证
  if (token) {
    // defaultHeader.Authorization = `Bearer ${token}`
    defaultHeader.Authorization = `${token}`
  }
  // 合并头信息
  options.header = Object.assign({}, defaultHeader, options.header)
  // 拦截器处理后的请求参数
  return options
}
// 响应拦截器
http.intercept.response = ({ statusCode, data }) => {
  const app = getApp()
  if (statusCode === 401) {
    // 清空token
    app.setToken('token', '')
    // 回到登录页
    const pages = getCurrentPages()
    const curPage = pages[pages.length - 1]
    wx.redirectTo({ url: '/pages/login/login?redirectURL=/' + curPage.route })
    return Promise.reject('登录信息过期,请重新登录')
  }
  if (data.code === 200) {
    return data.data
  } else {
    return Promise.reject(data.message)
  }
}
wx.$request = http
export default http

